import React,{Component} from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import {Flex,ImagePicker,Toast,ActivityIndicator} from 'antd-mobile';
import styles from './Authentication.css'
import imageCompress from '../../../../../../../framework/utils/imageCompress';
import { createForm } from 'rc-form';

import CustBtn from '../../../../../../../common/buttons/Btn';

// CusSubmitBtn
import arrowIcon from '../../../../../../../icons/personal/arrow.png';
import writeIcon from '../../../../../../../icons/personal/write-icon.png';

const defaultIdPositive = require('../../../../../../../assets/idPositive.png');
const defaultIdNegative = require('../../../../../../../assets/idNegative.png');
const bankImg = require('../../../../../../../assets/bank.png');

class Authentication extends Component{
  constructor(props) {
    super(props);
    this.state = {
      files: [],
      positiveImgUrl: defaultIdPositive,//idPositive
      nagetiveImgUrl: defaultIdNegative,//idNegative
      bankCardImgUrl: bankImg,
      positiveImgData:'',
      nagetiveImgData:'',
      bankCardImgData:'',
      animating:false,
      uploadImgs: [],
      onUploadImg: this.props.onUploadImg,
      isVerification:false,
    };
  }


    componentDidMount(){
      const { personalData } = this.props;
      let idcardFront = '';
      let idcardBack = '';
      let bankcardSnapshot = '';
      let verification = '';
      if(personalData){
        if(personalData.profile){
          verification = personalData.verification;
          idcardFront = personalData.profile.idcardFront;
          idcardBack = personalData.profile.idcardBack
          bankcardSnapshot = personalData.profile.bankcardSnapshot
        }
      }
      let isVerification = false;
      if(verification == 'PASS' || verification == 'AUTHENTICATING'){
        isVerification = true;
      }
      this.setState({
        isVerification,
        positiveImgUrl: idcardFront ? idcardFront : defaultIdPositive,
        nagetiveImgUrl: idcardBack ? idcardBack : defaultIdNegative,
        bankCardImgUrl: bankcardSnapshot ? bankcardSnapshot : bankImg,
      })

    }

  complete = () =>{

    this.props.form.validateFields((error, value) => {

      if (error) {
        for (var i in error) {
          error[i].errors.map(e => Toast.info(e.message, 2, null, false));
        }
        return;
      }

      // let isCard = '^\d{15}|\d{}18$';
      // if(!isCard.test(value.idCardNumber)){
      //   Toast.info("请输入有效的身份证号码", 2, null, false)
      // }

      const isIDCard1=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      if(!isIDCard.test(value.idCardNumber)){
        Toast.info("请输入有效的身份证号码", 2, null, false)
        return;
      }

      let uploadImgs = [];

      let positiveImg = this.state.positiveImgData;
      let nagetiveImg = this.state.nagetiveImgData;
      let bankCardImg = this.state.bankCardImgData;

      if(positiveImg != ''){
        uploadImgs.push(this.state.positiveImgData);
      }
      if(nagetiveImg != ''){
        uploadImgs.push(this.state.nagetiveImgData);
      }
      if(bankCardImg != ''){
        uploadImgs.push(this.state.bankCardImgData);
      }

      // console.log('uploadImgs.length', uploadImgs.length);
      if(!uploadImgs || uploadImgs.length < 3){
        Toast.info("请上传身份证正面反面照片", 2, null, false)
        return;
      }
      value.files = uploadImgs;
      // console.log('submit', JSON.stringify(value));
      // return;

      this.props.submit(value)
    });
  }

  imgPositive = () =>{
    console.log('imgPositive click')
    if(this.state.isVerification){
      return;
    }
    document.getElementById("idPositive").click();
  }
  imgNegative = () =>{
    console.log('imgNegative click')
    if(this.state.isVerification){
      return;
    }
    document.getElementById("idNegative").click();
  }
  imgBankCard = () =>{
    if(this.state.isVerification){
      return;
    }
    document.getElementById("idBankCard").click();
  }

  positiveChange = (event) => {
    let files = event.target.files, file;
    if (files && files.length > 0) {
      imageCompress.convertInputImgae(files, 800, (base64Url,imgURL) => {
        const ImgArr = {imgURL: imgURL,base64Url: base64Url,key:'idcardFront'}
        this.props.onUploadImg(ImgArr)
        this.setState({
          positiveImgUrl : imgURL,
          positiveImgData: base64Url,
        });
      });
    }
  }

  negativeChange = (event) => {
    let files = event.target.files, file;
    if (files && files.length > 0) {
      imageCompress.convertInputImgae(files, 800, (base64Url,imgURL) => {
        const ImgArr = {imgURL:imgURL,base64Url: base64Url,key:'idcardBack'}
        this.props.onUploadImg(ImgArr)

        this.setState({
          nagetiveImgUrl : imgURL,
          nagetiveImgData : base64Url
        });
      });
    }
  }
  bankCardChange = (event) => {
    let files = event.target.files, file;
    if (files && files.length > 0) {
      imageCompress.convertInputImgae(files, 800, (base64Url,imgURL) => {
        const ImgArr = {imgURL: imgURL,base64Url: base64Url,key:'bankcardSnapshot'}
        this.props.onUploadImg(ImgArr)

        this.setState({
          bankCardImgUrl : imgURL,
          bankCardImgData : base64Url
        });
      });
    }
  }


    render(){
      const { files,submit,positiveImgData,nagetiveImgData,
        bankCardImgData,uploadImgs,isVerification } = this.state
      const { getFieldProps, getFieldError, getFieldDecorator, setFieldsValue,validateFields } = this.props.form;
      const { loading,goBack,onSubmit,profile, isValidate,personalData } = this.props;

      if(loading){
        this.state.animating = true ;
      }else{
        this.state.animating = false ;
      }

      const isIDCard1=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/

      const validData = () => {

        // const { personalData } = this.props;

        validateFields((error, value) => {
          // console.log(error, value);
          if (error) {
            for (var i in error) {
              error[i].errors.map(e => Toast.info(e.message, 1.5))
            }
            return;
          } else if( !isIDCard1.test(value.idcardNo)){
            Toast.info('请输入有效的身份证号码', 1.5)
          }  else if(value.bankcardNo.length<18){
            Toast.info('请输入有效的银行卡号', 1.5)
          } else if(!positiveImgData && !personalData.profile.idcardFront) {
            Toast.info('请上传身份证正面照', 1.5)
          } else if(!nagetiveImgData && !personalData.profile.idcardBack) {
            Toast.info('请上传身份证背面照', 1.5)
          } else if(!bankCardImgData && !personalData.profile.bankcardSnapshot) {
            Toast.info('请上传银行卡照片', 1.5)
          } else {
            // Toast.info('已提交', 1.5)
            // value.positiveImgData = positiveImgData
            // value.nagetiveImgData = nagetiveImgData
            // value.bankCardImgData = bankCardImgData
            onSubmit(value)
          }
          // console.log('value', JSON.stringify(value))
        });
      }

      const showBtn = (isValidate) =>{

        if(isValidate){
          return;
        }

        const btnProps = {
          textValue:'提交',
          onOk(){
            validData();
          },
        }
        return (
          <div>
            <MarginBottom/>
            <div className={styles.footBtn}>
              <CustBtn {...btnProps} />
            </div>
          </div>
        )
      }


      const MarginBottom = () => <div style={{height: '3em', backgroundColor:'#F5F5F9'}}></div>;
      const CutTextHeight = () => <div style={{height: '1em', backgroundColor:'#FFF'}}></div>;

      return(
        <div className={styles.content}>
          <div className={styles.title}>
            <img src={arrowIcon} className={styles.titleIcon} onClick={() => goBack()}/>
            <div className={styles.titleText}>身份认证</div>
            {/* <div className={styles.complete}>完成</div> */}
          </div>
          {/* <div style={{marginTop: '2.8125em'}}> */}
          <div>
            <div className={styles.part}>
            <div className={styles.text}>
              国家有关政策要求互联网兼职平台实行身份认证，兼职™平台必须配合，用户有义务遵守。
              所有隐私将依法依规被保护。
            </div>
            <CutTextHeight/>

              <div className={styles.enterName}>
                <div className={styles.headName}>真实姓名</div>
                {getFieldDecorator('name', {
                  initialValue:profile.name,
                  rules: [
                    { required: true, message: '请输入真实姓名' }
                  ]
                })(
                  // <TextareaItem rows={5} placeholder="正文" />
                  <input className={styles.inputName} disabled={isValidate}/>
                )}
              </div>
              <div className={styles.enterID}>
                <div className={styles.headID}>身份证号码</div>
                {getFieldDecorator('idcardNo', {
                  initialValue:profile.idcardNo,
                  rules: [
                    { required: true, message: '请输入身份证号码', }
                  ],
                })(
                  <input maxLength={18} className={styles.inputID} disabled={isValidate}/>
                )}
              </div>
              <div className={styles.enterBankCard}>
                <div className={styles.headName}>银行卡</div>
                {getFieldDecorator('bankcardNo', {
                  initialValue:profile.bankcardNo,
                  rules: [
                    { required: true, message: '请输入银行卡号' }
                  ],

                })(
                  // <TextareaItem rows={5} placeholder="正文" />
                    <input maxLength={18} className={styles.inputBankCard} disabled={isValidate}/>
                )}
              </div>

              <div className={styles.enterID}>
                {/* <div className={styles.head}>上传身份证照片(请务必按照示例上传)</div>
                <div className={styles.info}>
                  您上传的任何身份证照片等资料, 仅供审核使用且他人无法看到, 此外,
                  我们会对照片进行安全处理, 敬请放心。
                </div> */}

              </div>
              <div className={styles.upload}>

                <div className={styles.example1}>
                  <input
                    id='idPositive'
                    type='file'
                    name='idPositive'
                    onChange={(e) => this.positiveChange(e)}
                    style={{display:'none'}}
                  />
                  <img
                    src={this.state.positiveImgUrl}
                    className={styles.idPositive}
                    onClick={() => this.imgPositive()}
                  />
                  <div>身份证正面照</div>

                </div>
                <div className={styles.example2}>
                  <input
                    id='idNegative'
                    type='file'
                    name='idNegative'
                    onChange={(e) => this.negativeChange(e)}
                    style={{display:'none'}}
                  />
                  <img
                    src={this.state.nagetiveImgUrl}
                    className={styles.idNegative}
                    onClick={() => this.imgNegative()}
                  />
                  <div>身份证反面照</div>
                </div>
                <div className={styles.example3}>
                  <input
                    id='idBankCard'
                    type='file'
                    name='idBankCard'
                    onChange={(e) => this.bankCardChange(e)}
                    style={{display:'none'}}
                  />
                  <img
                    src={this.state.bankCardImgUrl}
                    className={styles.card}
                    onClick={() => this.imgBankCard()}
                  />
                  <div>银行卡照片</div>
                </div>

              </div>
            </div>
              {showBtn(isValidate)}
          </div>

          <ActivityIndicator
            toast
            text="上传中..."
            animating={this.state.animating}
          />
        </div>
      )
    }
}

const AuthenticationWrapper = createForm()(Authentication);
export default connect()(AuthenticationWrapper);
